package com.yt.order.service;

import com.yt.common.utils.StrUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import com.yt.order.common.config.YmlConfig;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yt.order.mapper.WorkOrderInfoMapper;
import com.yt.order.models.service.IWorkOrderInfoService;
import com.yt.order.models.bo.WorkOrderInfoSaveBO;
import com.yt.order.models.dto.WorkOrderInfoDTO;
import lombok.extern.slf4j.Slf4j;
/**
 * 工单控制器
 *
 * @author xieyanfei
 * @Date 2025-09-04 21:53:07
 */
@Slf4j
@DubboService
public class WorkOrderInfoServiceImpl extends ServiceImpl<WorkOrderInfoMapper, WorkOrderInfoDTO> implements IWorkOrderInfoService{

    @Resource
    private YmlConfig ymlConfig;

    @Override
    public boolean add(WorkOrderInfoSaveBO saveBO) {
        WorkOrderInfoDTO dto = new WorkOrderInfoDTO();
        BeanUtils.copyProperties(saveBO,dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        return this.insert(dto);
    }

    /**
     * 状态变更为进行中（仅允许从"未派单"状态变更）
     * 假设：0=未派单，1=进行中
     */
    @Override
    public boolean changeToInProgress(Long id) {
        WorkOrderInfoDTO dto = this.selectById(id);
        if (dto == null) {
            log.error("工单不存在，id:{}", id);
            return false;
        }

        // 状态校验：仅未派单(0)可变更为进行中(1)
        if (dto.getStatus() != 0) {
            log.error("工单状态错误，当前状态:{}，id:{}", dto.getStatus(), id);
            return false;
        }

        dto.setStatus(1);
        return this.updateById(dto);
    }

    /**
     * 拒绝工单
     * 假设：2=已拒绝
     */
    @Override
    public boolean rejectOrder(Long id, String reason) {
        WorkOrderInfoDTO dto = this.selectById(id);
        if (dto == null) {
            log.error("工单不存在，id:{}", id);
            return false;
        }

        // 记录拒绝原因到描述字段
        String originalDes = StrUtils.isEmpty(dto.getDes()) ? "" : dto.getDes();
        dto.setDes(originalDes + "【拒绝原因：" + reason + "】");
        dto.setStatus(2);

        return this.updateById(dto);
    }
}
